package com.meng.thrift.server.thrift.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;


/**
 * @PublishThriftServer 解析类
 *
 * @author MENG
 * @version 2017/11/22
 * @see
 */
@Component
public class PublishThriftServerAnalysis implements BeanPostProcessor
{
    //bean 初始化之前
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
        throws BeansException
    {

        return bean;
    }

    //bean 初始化之后
    // （ 也可以 反射执行 获取所有属性名称  并为该属性赋值,可实现@ConfigurationProperties(prefix,locations)注解）
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
        throws BeansException
    {
        //get @PublishThriftServer decorate class 这边实现发布服务
        if(bean.getClass().isAnnotationPresent(PublishThriftServer.class))
        {
            PublishThriftServer obj = bean.getClass().getAnnotation(PublishThriftServer.class);

            int port = obj.port();

            //获取类实现的所有接口
            Class<?> interfaces[] = bean.getClass().getInterfaces();

            String interfaceClassPath = "";

            for (int i = 0; i < interfaces.length; i++)
            {
                //内部接口类路径
                String insideInterfaceClassPath = interfaces[i].getName();

                String str = insideInterfaceClassPath.substring(insideInterfaceClassPath.lastIndexOf("$")+1);

                //Iface thrift特殊接口名称
                if(("Iface").equals(str))
                {
                    //外部接口类路径
                    interfaceClassPath = insideInterfaceClassPath.substring(0,insideInterfaceClassPath.lastIndexOf("$"));

                    System.out.println(interfaceClassPath);

                    //当实现多个thrift接口情况，因为一个接口服务端口不能一样，一样的端口只有第一次发布的服务可用，
                    // 所以没有必要同个端口同个实现类情况下,发布多个接口服务
                    break;
                }
            }

            if(!interfaceClassPath.equals(""))
            {
                ThriftServerProxy serverProxy = new ThriftServerProxy(port,interfaceClassPath,bean);

                //开启线程  发布thrift server
                Thread thread = new Thread(serverProxy);

                thread.start();
            }
        }

        return bean;
    }
}
